package logic

import (
	"context"
	"fmt"
	"house_srv/houseclient"
	"net/http"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateStatusLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateStatusLogic {
	return &UpdateStatusLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateStatusLogic) UpdateStatus(w http.ResponseWriter, r *http.Request) (resp *types.UpdateStatusResponse, err error) {
	// todo: add your logic here and delete this line

	fmt.Println("触发了回调")
	logx.Info(r.FormValue("out_trade_no"))
	logx.Info(r.FormValue("trade_status"))
	fmt.Println("触发了回调")

	//WAIT_BUYER_PAY	交易创建，等待买家付款。
	//TRADE_CLOSED	未付款交易超时关闭，或支付完成后全额退款。
	//TRADE_SUCCESS	交易支付成功。
	//TRADE_FINISHED	交易结束，不可退款。

	orderSn := r.FormValue("out_trade_no")
	status := r.FormValue("trade_status")
	var OrderStatus int

	if status == "TRADE_CLOSED" {
		OrderStatus = 5
	} else if status == "TRADE_SUCCESS" {
		OrderStatus = 2
	} else if status == "TRADE_FINISHED" {
		OrderStatus = 4
	} else {
		return
	}

	l.svcCtx.HouseRpc.UpdateStatus(l.ctx, &houseclient.UpdateStatusRequest{
		OrderSn:     orderSn,
		HouseStatus: int64(OrderStatus),
	})

	w.Write([]byte("success"))
	return
}
